import {
  ScrollView,
  TouchableOpacity,
  View,
  Text,
  StyleSheet,
  Image,
} from 'react-native';
import React, {useEffect, useRef, useState} from 'react';

import icon_arrow from '../../../assets/icon_arrow.png';
import CategoryModal, {CategoryModalRef} from './CategoryModal';
type CategoryListProps = {
  categoryList: Category[];
  onCategoryChanged: (category: Category) => void;
};
export default ({categoryList, onCategoryChanged}: CategoryListProps) => {
  const modalRef = useRef<CategoryModalRef>(null);
  const [category, setCategory] = useState<Category>();
  useEffect(() => {
    const cat = categoryList.find(item => item.name === '推荐');
    setCategory(cat);
  }, [categoryList]);
  const onCategoryPress = (cate: Category) => {
    setCategory(cate);
    onCategoryChanged?.(cate);
  };
  const myList = categoryList.filter(item => item.isAdd === true);
  return (
    <View style={styles.container}>
      <ScrollView
        style={styles.scrollView}
        horizontal={true}
        showsHorizontalScrollIndicator={false}>
        {myList.map((item: Category) => {
          const isSelected = category?.name === item.name;
          return (
            <TouchableOpacity
              key={`${item.name}`}
              style={styles.tabItem}
              onPress={() => onCategoryPress(item)}>
              <Text style={isSelected ? styles.tabTxtSelected : styles.tabTxt}>
                {item.name}
              </Text>
            </TouchableOpacity>
          );
        })}
      </ScrollView>
      <TouchableOpacity
        style={styles.iconButton}
        onPress={() => {
          modalRef.current?.show();
        }}>
        <Image style={styles.icon} source={icon_arrow} />
      </TouchableOpacity>

      <CategoryModal ref={modalRef} AllCategoryList={categoryList} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: 40,
    backgroundColor: 'white',
    flexDirection: 'row',
    marginBottom: 6,
    justifyContent: 'center',
    alignItems: 'center',
  },
  scrollView: {
    flex: 1,
    height: '100%',
  },
  tabItem: {
    height: '100%',
    width: 62,
    alignItems: 'center',
    justifyContent: 'center',
  },
  tabTxt: {
    fontSize: 16,
    color: 'gray',
  },
  tabTxtSelected: {
    fontSize: 18,
  },
  iconButton: {
    height: '100%',
    width: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  icon: {
    width: 18,
    height: 18,
    transform: [{rotate: '-90deg'}],
  },
});
